<template>
    <el-row>
        <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
            <el-form :inline="true" :model="filter" class="demo-form-inline">
                <el-form-item label="客户信息">
                    <el-input v-model="filter.mixedLikeInfo" placeholder="名称/联系人/电话/备注" clearable />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="filter.enable" placeholder="全部">
                        <el-option label="全部" :value="null" />
                        <el-option label="启用" :value="true" />
                        <el-option label="停用" :value="false" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
            <el-button icon="Plus" @click="createCustomer" type="primary">新建客户</el-button>
            <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
            <el-table v-loading="loading" :data="dataList" style="width: 80%; min-width: 600px; height: 100%;">
                <el-table-column label="客户名称" align="center">
                    <template #default="scope">
                        <span>
                            {{ scope.row.name }}
                            <el-tag v-if="scope.row.enabled === false" size="small" type="danger"
                                style="margin-left: 8px;">
                                停用
                            </el-tag>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="联系人" align="center" prop="contactName"></el-table-column>
                <el-table-column label="联系电话" align="center" prop="contactPhoneNumber"></el-table-column>
                <el-table-column label="城市" align="center" prop="city"></el-table-column>
                <el-table-column label="地址" align="center" prop="address"></el-table-column>
                <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <template v-if="isPlatformCustomer(scope.row)">
                            - -
                        </template>
                        <template v-else>
                            <el-link :underline="false" type="danger" @click="delCustomer(scope.row)">
                                删除
                            </el-link>
                            <el-link :underline="false" style="margin-left: 24px;" type="primary"
                                @click="showDetailPage(scope.row)">
                                详情
                            </el-link>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>

    <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 编辑对话框  -->
    <customer-basic-info-dialog ref="editDialog" mode="edit" @submit="handleCreatedCustomer" />
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage, NetworkParser } from '../../public/network/communicationConverter'
import { useRouter } from 'vue-router'
import EventBus from '../../public/engine/ipc/eventBus'
import { Customer, CustomerFilter } from '../../public/engine/targetOrg/customer'
import { deleteTargetObjectNetworkCache } from '../../public/network/api'
import { TargetObjectPlatformType } from '../../public/engine/targetOrg/targetObject'
import { removeCustomer } from '../../public/network/api'
import CustomerBasicInfoDialog from './customerBasicInfoDialog.vue'

export default {
    name: 'customers',
    components: {
        CustomerBasicInfoDialog
    },
    data() {
        return {
            total: 0,
            loading: false,
            queryParams: {
                pageNum: 1,
                pageSize: Definition.gDefualPageSize,
            },
            searchForm: {
                name: '',
                contactName: '',
                contactPhoneNumber: ''
            },
            dataList: [],
            basicUiAction: new BasicUiAction(),
            router: useRouter(),
            filter: new CustomerFilter(),
        }
    },
    methods: {

        isPlatformCustomer(customer) {
            // console.log("---> isPlatformCustomer:", customer.objPlatformType)
            return customer.platformType == TargetObjectPlatformType.TPlatformCreated;
        },

        handleSearch() {
            this.getList();
        },

        resetSearch() {
            this.filter.clear()
            this.getList();
        },

        refreshList() {
            // 删除缓存，重新请求
            deleteTargetObjectNetworkCache();
            this.getList();
        },
        async getList() {
            try {
                this.loading = true
                const res = await this.basicUiAction.getCustomerData({
                    pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
                    filter: this.filter.toJson(),
                })

                if (res && res.data && res.data.dataList) {
                    this.dataList = res.data.dataList
                    this.total = res.data.pageInfo?.total || res.data.dataList.length
                } else if (res?.resErr) {
                    console.error('获取客户列表失败', res?.resErr)
                    ElMessage.error('获取客户列表失败')
                }
            } catch (error) {
                console.error('获取客户列表失败', error)
                ElMessage.error('获取客户列表失败')
            } finally {
                this.loading = false
            }
        },

        createCustomer() {
            this.$refs.editDialog.open(Customer.empty());
        },

        showDetailPage(customer) {
            this.router.push({
                path: '/partners/customer',
                query: {
                    id: customer.id,
                    type: 'detail'
                }
            })
        },

        delCustomer(customer) {
            ElMessageBox.confirm(
                `确定要删除客户【${customer.name}】吗？`,
                '删除确认',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            this.handleRemoveCustomer(customer)
                                .finally(() => {
                                    instance.confirmButtonLoading = false
                                    done()
                                })
                        } else {
                            done()
                        }
                    }
                }
            ).catch(() => {
                ElMessage.info('删除操作已取消')
            })
        },

        async handleRemoveCustomer(customer) {
            if (!customer.id) {
                return;
            }

            try {
                const res = await removeCustomer(customer.id)
                let reqResult = NetworkParser.parseNetworkResult(res, null);

                if (reqResult.resErr != null) {
                    console.error('删除客户失败', reqResult.resErr)
                    ElMessage.error("删除客户失败:" + reqResult.resErr)
                    return
                } else if (reqResult.data != null) {
                    ElMessage.success('删除客户成功')
                    this.refreshList();
                }
            } catch (error) {
                console.error('删除客户失败', error)
                ElMessage.error("删除客户失败:" + error)
            }
        },

        handleCustomerUpdated() {
            this.getList()
        },

        // 新建供应商回调
        handleCreatedCustomer({ type, data }) {
            // 刷新数据列表
            this.refreshList();
        },
    },
    mounted() {
        this.getList()
        EventBus.on('customerUpdated', this.handleCustomerUpdated)
    },
    beforeUnmount() {
        EventBus.off('customerUpdated', this.handleCustomerUpdated)
    }
}
</script>